<template>
  <div class="result-show-container">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="类别统计" name="categoryStats">
        <div v-if="activeTab === 'categoryStats'">
          <div class="top-row">
            <el-card>
              <p>分析结果：</p>
              <p>{{ analysisContent }}</p>
            </el-card>
          </div>
          <div class="top-row">
            <el-card class="scale-card">
              <p>调整前功能点总数</p>
              <p class="scale-value">{{ categoryStatsData[5].value }}</p>
            </el-card>
            <el-card class="scale-card">
              <p>调整后功能点总数</p>
              <p class="scale-value">{{ categoryStatsData[6].value }}</p>
            </el-card>
          </div>
          <div class="bottom-row">
            <el-card class="stats-card">
              <p>类别统计</p>
              <el-table :data="categoryStatsData.slice(0, 5)" style="width: 100%; margin-top: 20px">
                <el-table-column prop="name" label="项" width="150"></el-table-column>
                <el-table-column prop="value" label="数量"></el-table-column>
              </el-table>
            </el-card>
            <el-card class="chart-card">
              <p>功能点统计</p>
              <div id="bar-chart" class="bar-chart"></div>
            </el-card>
          </div>
        </div>
      </el-tab-pane>
      <!-- <el-tab-pane label="团队管理" name="teamManagement">
        <div v-if="activeTab === 'teamManagement'">
          <el-card>
            <p>团队管理</p>
          </el-card>
        </div>
      </el-tab-pane> -->
      <el-tab-pane label="参数调整" name="parameterAdjustment">
        <div v-if="activeTab === 'parameterAdjustment'">
          <div class="project-confirm-container" style="margin-top: 0px;">
            <el-table :data="complexityData" style="width: 100%; margin-top: 20px">
              <el-table-column prop="name" label="复杂度" width="150"></el-table-column>
              <el-table-column label="值">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.value" placeholder="请输入"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <el-select v-model="selectedOption" placeholder="请选择" style="width: 200px; margin-top: 20px">
              <el-option label="通用系统调整因子法" value="GSC"></el-option>
              <el-option label="需求变更调整因子法" value="VAF"></el-option>
            </el-select>
            <el-table v-if="selectedOption === 'GSC'" :data="gscData" style="width: 100%; margin-top: 20px">
              <el-table-column prop="name" label="项" width="250"></el-table-column>
              <el-table-column label="值">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.value" :placeholder="`初始值: ${scope.row.initialValue}`"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="selectedOption === 'VAF'">
              <el-select v-model="selectedSection" placeholder="请选择" style="width: 200px; margin-top: 20px" @change="handleSectionChange">
                <el-option label="项目立项" value="initiation"></el-option>
                <el-option label="项目招标" value="bidding"></el-option>
                <el-option label="项目早期" value="early"></el-option>
                <el-option label="项目中期" value="midterm"></el-option>
                <el-option label="项目完成" value="completion"></el-option>
              </el-select>
              <div v-if="selectedSection">
                <p>{{ sectionMap[selectedSection] }}</p>
                <el-input v-model="cf" :placeholder="`默认值: ${defaultSectionValues[selectedSection]}`"></el-input>
              </div>
            </div>
            <el-button type="primary" style="margin-top: 20px" @click="proceedToNextStep">
              确认
            </el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';

export default {
  name: 'ResultShow',
  props: ['id'],
  data() {
    return {
      activeTab: 'categoryStats',
      categoryStatsData: [
        { name: 'EO数量', value: 0 },
        { name: 'EI数量', value: 0 },
        { name: 'EQ数量', value: 0 },
        { name: 'ILF数量', value: 0 },
        { name: 'EIF数量', value: 0 },
        { name: '调整前功能点总数', value: 0 },
        { name: '调整后功能点总数', value: 0 },
      ],
      analysisContent: '',
      complexityData: [
        { name: 'EO复杂度', value: '' },
        { name: 'EI复杂度', value: '' },
        { name: 'EQ复杂度', value: '' },
        { name: 'ILF复杂度', value: '' },
        { name: 'EIF复杂度', value: '' },
      ],
      selectedOption: '',
      selectedSection: '',
      cf: 0,  // 需求变更因子法系数
      gscData: [
        { name: '分布式数据处理', value: 0, initialValue: 0 },
        { name: '性能', value: 0, initialValue: 0 },
        { name: '重度配置', value: 0, initialValue: 0 },
        { name: '处理速率', value: 0, initialValue: 0 },
        { name: '在线数据输入', value: 0, initialValue: 0 },
        { name: '最终用户使用效率', value: 0, initialValue: 0 },
        { name: '在线升级', value: 0, initialValue: 0 },
        { name: '复杂处理', value: 0, initialValue: 0 },
        { name: '可重用性', value: 0, initialValue: 0 },
        { name: '易安装性', value: 0, initialValue: 0 },
        { name: '易操作性', value: 0, initialValue: 0 },
        { name: '多场所', value: 0, initialValue: 0 },
        { name: '支持变更', value: 0, initialValue: 0 },
        { name: '数据通信', value: 0, initialValue: 0 },
      ],
      vafData: [
        { name: 'EI数量', value: 0 },
        { name: 'EO数量', value: 0 },
        { name: 'EQ数量', value: 0 },
        { name: 'ILF数量', value: 0 },
        { name: 'EIF数量', value: 0 },
        { name: '项目立项', value: 0, key: 'initiation' },
        { name: '项目招标', value: 0, key: 'bidding' },
        { name: '项目早期', value: 0, key: 'early' },
        { name: '项目中期', value: 0, key: 'midterm' },
        { name: '项目完成', value: 0, key: 'completion' },
      ],
      fetchedData: null,
      paramId: null,
      defaultSectionValues: {
        initiation: 2.00,
        bidding: 1.50,
        early: 1.26,
        midterm: 1.26,
        completion: 1.00
      },
      sectionMap: {
        initiation: '项目立项',
        bidding: '项目招标',
        early: '项目早期',
        midterm: '项目中期',
        completion: '项目完成',
      }
    };
  },
  mounted() {
    this.fetchCategoryStatsData();
    this.fetchGSCData();
    this.$nextTick(() => {
      this.initChart();
    });
  },
  methods: {
    async fetchCategoryStatsData() {
      try {
        const response = await axios.get(`http://localhost:8080/param/detail?id=${this.id}`, {
          headers: {
            token: 'your-token-here'
          }
        });
        const data = response.data.data;
        this.fetchedData = data;

        this.categoryStatsData[0].value = data.eo;
        this.categoryStatsData[1].value = data.ei;
        this.categoryStatsData[2].value = data.eq;
        this.categoryStatsData[3].value = data.ilf;
        this.categoryStatsData[4].value = data.eil;
        this.categoryStatsData[5].value = data.resultUfp;
        this.categoryStatsData[6].value = data.resultChanged;
        this.analysisContent = data.analysisContent;
        this.initChart();
      } catch (error) {
        console.error('Error fetching category stats data:', error);
      }
    },
    async fetchGSCData() {
      try {
        const response = await axios.get(`http://localhost:8080/param/getParam?projectId=${this.id}`, {
          headers: {
            token: 'your-token-here'
          }
        });

        const data = response.data.data;

        this.paramId = data.id;

        const nameToKeyMap = {
          'EO复杂度': 'eoParam',
          'EI复杂度': 'eiParam',
          'EQ复杂度': 'eqParam',
          'ILF复杂度': 'ilfParam',
          'EIF复杂度': 'eilParam',

          '数据通信': 'dc',
          '分布式数据处理': 'ddp',
          '性能': 'performance',
          '重度配置': 'huc',
          '处理速率': 'tr',
          '在线数据输入': 'ode',
          '最终用户使用效率': 'eue',
          '在线升级': 'ou',
          '复杂处理': 'cp',
          '可重用性': 'reu',
          '易安装性': 'ie',
          '易操作性': 'oe',
          '多场所': 'ms',
          '支持变更': 'fc',
          '功能点总系数': 'ufp',

          'EI数量': 'ei',
          'EO数量': 'eo',
          'EQ数量': 'eq',
          'ILF数量': 'ilf',
          'EIF数量': 'ell',
        };

        this.gscData.forEach(item => {
          const key = nameToKeyMap[item.name];
          const fetchedValue = data[key];
          item.initialValue = fetchedValue || 0;
          item.value = item.initialValue;
        });

        this.complexityData.forEach(item => {
          const key = nameToKeyMap[item.name];
          const fetchedValue = data[key];
          item.value = fetchedValue || 0;
        });

        this.vafData.forEach(item => {
          const key = nameToKeyMap[item.name] || item.key;
          const fetchedValue = data[key];
          item.value = fetchedValue || 0;
        });

      } catch (error) {
        console.error('Error fetching GSC data:', error);
      }
    },
    handleSectionChange() {
      if (this.selectedSection) {
        this.cf = this.defaultSectionValues[this.selectedSection];
      }
    },
    async proceedToNextStep() {
      try {
        const id = this.paramId;

        const nameToKeyMap = {
          'EO复杂度': 'eoParam',
          'EI复杂度': 'eiParam',
          'EQ复杂度': 'eqParam',
          'ILF复杂度': 'ilfParam',
          'EIF复杂度': 'eilParam',
          // 其他复杂度参数
          '数据通信': 'dc',
          '分布式数据处理': 'ddp',
          '性能': 'performance',
          '重度配置': 'huc',
          '处理速率': 'tr',
          '在线数据输入': 'ode',
          '最终用户使用效率': 'eue',
          '在线升级': 'ou',
          '复杂处理': 'cp',
          '可重用性': 'reu',
          '易安装性': 'ie',
          '易操作性': 'oe',
          '多场所': 'ms',
          '支持变更': 'fc',
          '功能点总系数': 'ufp',
        };

        const params = this.gscData.reduce((acc, item) => {
          const backendKey = nameToKeyMap[item.name] || item.name;
          acc[backendKey] = Number(item.value);
          return acc;
        }, {});

        this.complexityData.forEach(item => {
          const backendKey = nameToKeyMap[item.name];
          if (backendKey) {
            params[backendKey] = Number(item.value) || 0;
          }
        });

        // 设置 methodType 参数
        if (this.selectedOption === 'VAF') {
          params.methodType = 1;
          params.cf = Number(this.cf) || this.defaultSectionValues[this.selectedSection];
        } else if (this.selectedOption === 'GSC') {
          params.methodType = 0;
        }

        params.id = id;

        console.log('Sending parameters:', params);

        const response = await axios.put('http://localhost:8080/param', params, {
          headers: {
            token: 'your-token-here'
          }
        });

        console.log('Response from server:', response);

        this.$message.success('参数更新成功');
      } catch (error) {
        console.error('Error updating parameters:', error);
        this.$message.error('参数更新失败');
      }
    },
    handleTabClick(tab) {
      this.activeTab = tab.name;
      if (tab.name === 'categoryStats') {
        this.fetchCategoryStatsData();
        this.$nextTick(() => {
          this.initChart();
        });
      } else if (tab.name === 'teamManagement') {
        // Add logic if needed for team management tab
      } else if (tab.name === 'parameterAdjustment') {
        this.fetchGSCData();
      }
    },
    initChart() {
      const chartDom = document.getElementById('bar-chart');
      if (!chartDom) {
        console.warn('Chart DOM element not found');
        return;
      }
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '功能点统计'
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: ['EO', 'EI', 'EQ', 'ILF', 'EIF']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: this.categoryStatsData.slice(0, 5).map(item => item.value),
            type: 'bar',
            barWidth: '70%'
          }
        ]
      };
      myChart.setOption(option);
    },
    isVisible(name) {
      return this.sectionMap[this.selectedSection] === name;
    },
  },
};
</script>

<style scoped>
.result-show-container {
  padding: 20px;
}

.top-row,
.bottom-row {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  gap: 20px;
  margin-bottom: 20px;
}

.scale-card {
  flex: 0 0 auto;
  width: 300px;
  text-align: center;
}

.scale-value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 10px;
}

.stats-card {
  flex: 0 0 auto;
  width: 500px;
}

.chart-card {
  flex: 0 0 auto;
  width: 400px;
}

.bar-chart {
  width: 100%;
  height: 300px;
}

.project-confirm-container {
  padding: 20px;
}
</style>
